package com.example.navigation;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    // 底部导航栏
    private BottomNavigationView bottomNavigationView;

    // 底部导航栏按钮对应的id
    private int[] navigationButtonId = {R.id.home, R.id.shopping_cart, R.id.order, R.id.mine};

    // 底部导航栏按钮对应的几个Fragment的类
    private Class[] FragmentsClass = {
            HomeFragment.class,
            ShoppingCartFragment.class,
            OrderFragment.class,
            MineFragment.class};

    // 对应的Fragment对象，如果直接都new出来可能会造成卡顿，而且也用户不一定会使用到所有的Fragment浪费资源
    private Fragment[] fragments = new Fragment[FragmentsClass.length];


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取底部导航栏
        bottomNavigationView = findViewById(R.id.bottomNavigationView);

        // 默认首页
        changeFragment(0);

        // 设置点击事件
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            for (int i = 0; i < navigationButtonId.length; i++) {
                if (item.getItemId() == navigationButtonId[i]) {
                    // 切换Fragment
                    changeFragment(i);
                    break;
                }
            }
            return true;
        });

    }

    private void changeFragment(int index) {
        if (index < 0 || index >= fragments.length)  {
            return;
        }

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        for (int i = 0; i < fragments.length; i++) {
            // 要显示的这个Fragment
            if (index == i) {
                // 初始化
                if (fragments[i] == null) {
                    try {
                        fragments[i] = (Fragment) FragmentsClass[i].newInstance();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    }
                    // 添加到内容
                    transaction.add(R.id.content, fragments[i]);
                }
                // 显示
                transaction.show(fragments[i]);
            }
            // 不要显示的Fragment
            else {
                if (fragments[i] != null) {
                    // 隐藏
                    transaction.hide(fragments[i]);
                }
            }
        }

        // 一定要提交，不然没有效果
        transaction.commit();

    }
}